<template>
  <div class="style-edit">
    <section v-if="!isSelectMark" class="style-edit-empty">请选择绘制区域中的标绘方式</section>
    <section v-else class="style-edit-main">
      <header class="style-edit-main-header">
        <el-dropdown v-if="currStyleType" trigger="click" @command="onChangeEditStyleType">
          <el-button class="style-type-select" type="primary" plain>
            <span>{{ currStyleType }}</span>
            <el-icon class="style-type-select-icon"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="item in STYLE_TYPE_OPTIONS" :key="item.value" :command="item.label">{{ item.label }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-segmented class="menu" v-model="currMarkType" :options="markTypeList" @click="onMarkTypeClick"></el-segmented>
        <span class="segmented-tip" :class="{ 'show': isShowSegmentedTip }">当前为标绘样式编辑模式，仅可编辑区域绘制中所选标绘方式的样式</span>
      </header>
      <el-form class="style-edit-main-form" label-suffix="：" :model="styleConfigformData">
        <el-form-item v-for="item in currStyleConfigList" :key="item.key" :label="item.label" :prop="item.key">
          <el-input v-if="item.componentType === 'input'" v-model="styleConfigformData[item.key]" clearable placeholder="请输入" />
          <el-color-picker v-if="item.componentType === 'colorPicker'" v-model="styleConfigformData[item.key]" clearable />
          <el-input-number v-if="item.componentType === 'inputNumber'" v-model="styleConfigformData[item.key]" clearable
            placeholder="请输入" :min="0" :max="item.max ? item.max : Infinity" :step="item.step ? item.step : 1" />
          <el-select v-if="item.componentType === 'select'" v-model="styleConfigformData[item.key]" clearable placeholder="请选择">
            <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
          <el-radio-group v-if="item.componentType === 'radio'" v-model="styleConfigformData[item.key]">
            <el-radio v-for="option in item.options" :key="option.value" :value="option.value">{{ option.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <section v-if="currStyleType == STYLE_TYPE.DATA" class="form-action">
          <el-button @click="onResetStyle">重置</el-button>
          <el-button @click="onPreviewStyle">预览</el-button>
          <el-button type="primary" @click="onConfirmStyle">确定</el-button>
        </section>
      </el-form>
    </section>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import { eventBus } from '@/utils/eventBus';
import { MAP_EDIT_STYLE_OPTIONS, getBtnCtrlActiveOptions } from '@/components/Map/config';
import { STYLE_TYPE, STYLE_TYPE_OPTIONS } from '../config';
import { markApi } from '@/api/systemSetting'
import { ElMessage } from 'element-plus';
import { Plus, ArrowDown } from '@element-plus/icons-vue';

// const emits = defineEmits(['onStyleTypeChange'])
const props = defineProps({
  mapRef: {
    type: Object,
    default: () => ({}),
  },
});

onMounted(async () => {
  await nextTick();
  const mapReadyData = await props.mapRef.onMapReady();
  localMapEditor = mapReadyData.mapEditor;
  initFormData();
  getMarkList();
  eventBus.on('DrawSelect:onMarkerChange', onMarkerChange)
  eventBus.on('DrawSelect:onGetStyleConfig:request', onGetStyleConfig)
})

onBeforeUnmount(() => {
  eventBus.off('DrawSelect:onMarkerChange', onMarkerChange)
  eventBus.off('DrawSelect:onGetStyleConfig:request', onGetStyleConfig)
})

let localMapEditor = null;
let styleConfigformDataBak = null;
const currStyleType = defineModel('currStyleType');
const isShowSegmentedTip = ref(false);
const isSelectMark = ref(false);
const currMarkType = ref('');
const markTypeList = ref([]); // 就是标绘管理的markList
const styleConfigformData = reactive({});
const currStyleConfigList = computed(() => {
  const defaultStyleConfig = MAP_EDIT_STYLE_OPTIONS[currMarkType.value] ? MAP_EDIT_STYLE_OPTIONS[currMarkType.value] : {};
  return Object.entries(defaultStyleConfig).map(([key, item]) => ({ ...item, key }));
})

watch(() => currStyleType.value, type => {
  if (type == STYLE_TYPE.MARK) {
    markTypeList.value.forEach(item => item.disabled = item.value != currMarkType.value)
  } else {
    markTypeList.value.forEach(item => item.disabled = false)
    styleConfigformDataBak = { ...styleConfigformData };
  }
})

const onChangeEditStyleType = (value) => {
  currStyleType.value = value;
  // if (currStyleType.value == STYLE_TYPE.MARK) {
  //   currStyleType.value = STYLE_TYPE.DATA;
  // } else {
  //   currStyleType.value = STYLE_TYPE.MARK;
  // }
}

const initFormData = () => {
  Object.values(MAP_EDIT_STYLE_OPTIONS).forEach(typeConfig => {
    Object.entries(typeConfig).forEach(([key, item]) => styleConfigformData[key] = item.value)
  })
}

const onMarkerChange = checkNodeDataList => {
  isSelectMark.value = Array.isArray(checkNodeDataList) && checkNodeDataList.length >= 2;
  if (!isSelectMark.value) return;
  currStyleType.value = STYLE_TYPE.MARK;
  const markTypeItem = checkNodeDataList[0];
  // markTypeList.value = [{ label: markTypeItem.mc, value: markTypeItem.bh }];
  currMarkType.value = markTypeItem.bh;
}

const onMarkTypeClick = e => {
  const clickMarkTypeLabel = e.target.innerText;
  if (!clickMarkTypeLabel) return;
  const clickMarkTypeItem = markTypeList.value.find(item => item.label == clickMarkTypeLabel);
  if (!clickMarkTypeItem) return;
  // 若为编辑标绘模式，则提示用户
  if (currStyleType.value == STYLE_TYPE.MARK && currMarkType.value != clickMarkTypeItem.value) {
    isShowSegmentedTip.value = true;
    setTimeout(() => isShowSegmentedTip.value = false, 5000);
    return;
  }
  // 若为编辑数据模式，通知数据编辑组件，选中对应标绘类型的数据
  if (currStyleType.value == STYLE_TYPE.DATA) {
    eventBus.emit('StyleEdit:onSelectData', clickMarkTypeItem.value)
  }
}

const onGetStyleConfig = (markType) => {
  const defaultStyleConfig = MAP_EDIT_STYLE_OPTIONS[markType] ? MAP_EDIT_STYLE_OPTIONS[markType] : {};
  const currStyleConfig = Object.entries(defaultStyleConfig).reduce((acc, [key]) => {
    acc[key] = styleConfigformData[key];
    return acc;
  }, {})
  eventBus.emit('StyleEdit:onGetStyleConfig:response', getBtnCtrlActiveOptions(markType, currStyleConfig))
}

const getMarkList = async () => {
  try {
    const res = await markApi.asideList({});
    markTypeList.value = res.data.records.map(item => ({ ...item, label: item.mc, value: item.bh }));
  } catch (error) {
    console.error(error);
  }
}

const onResetStyle = () => {
  Object.assign(styleConfigformData, styleConfigformDataBak);
  // localMapEditor.cancelCustomStyle({ cancelSelected: false })
}

const onPreviewStyle = async () => {
  const selectedRowIds = await eventBus.requestData(
    'StyleEdit:onGetSelectedRowIds:request',
    'DataEdit:onGetSelectedRowIds:response',
  )
}

const onConfirmStyle = async () => {
  const selectedRowIds = await eventBus.requestData(
    'StyleEdit:onGetSelectedRowIds:request',
    'DataEdit:onGetSelectedRowIds:response',
  )
  localMapEditor.setFeaturePropertiesByIds(selectedRowIds, styleConfigformData);
  // localMapEditor.cancelCustomStyle({ cancelSelected: true })
  eventBus.emit('StyleEdit:onCancelSelectedRows')
}

defineExpose({ currMarkType })
</script>

<style lang="scss" scoped>
.style-edit {
  height: 100%;
  margin: 0 var(--ycy-gap-base);
  padding: var(--ycy-gap-base);
  border-radius: var(--el-border-radius-base);
  background-color: var(--el-fill-color-blank);

  .style-edit-empty {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: var(--el-font-size-base);
    color: var(--el-text-color-secondary);
  }

  .style-edit-main {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .style-edit-main-header {
      width: 100%;
      position: relative;
      display: flex;
      flex-direction: column;
      row-gap: var(--ycy-gap-base);

      .style-type-select {
        // font-size: var(--el-font-size-base);
        // color: var(--el-color-primary);
        cursor: pointer;
        // display: flex;
        // align-items: center;
        --el-button-hover-text-color: var(--el-color-primary);
        --el-button-hover-bg-color: var(--el-color-primary-light-9);
        --el-button-hover-border-color: var(--el-color-primary-light-5);

        &-icon {
          margin-left: calc(var(--ycy-gap-small) / 2);
          transition: var(--ycy-transition-base);

          &.option-visible {
            transform: rotateZ(180deg);
          }
        }
      }

      .segmented-tip {
        position: absolute;
        top: 100%;
        left: 0;
        color: var(--el-color-danger);
        font-size: 12px;
        line-height: 1;
        padding-top: 1px;
        opacity: 0;
        transform: translateY(-100%);
        transition: var(--ycy-transition-base);

        &.show {
          transform: translateY(0);
          opacity: 1;
        }
      }
    }

    .menu {
      width: max-content;
      border-radius: var(--el-border-radius-base);
  
      &.el-segmented {
        :deep(.el-segmented__item) {
          user-select: none;
          font-size: var(--el-font-size-base);
          padding: 4px 8px;
          margin-right: 8px;
  
          &:last-child {
            margin-right: 0;
          }
        }
  
        :deep(.el-segmented__item-label) {
          overflow: unset;
        }
      }
    }

    .style-edit-main-form {
      flex: 1;
      overflow: auto;
      margin-top: var(--ycy-gap-large);
      padding-right: calc(60px + var(--ycy-gap-large) * 2);
      position: relative;

      .form-action {
        position: absolute;
        right: var(--ycy-gap-large);
        bottom: 0;
        display: flex;
        flex-direction: column;

        .el-button {
          margin-left: 0;

          &:first-child {
            margin-bottom: var(--ycy-gap-base);
          }
        }
      }
    }
  }
}
</style>